package org.teemor.demo.nio.channel;

import org.junit.Test;
import org.teemor.demo.nio.BaseTest;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @Description:
 * @author zhoulk
 * @date: 2020/2/21
 */
public class ServerSocketChannelDemo implements BaseTest {

    @Test
    public void simpleTest() throws Exception{
        ServerSocketChannel server = ServerSocketChannel.open();
        server.socket().bind(new InetSocketAddress("localhost",8080));

        while (true) {
            SocketChannel socketChannel = server.accept();
            socketChannel.configureBlocking(true);
            ByteBuffer byteBuffer = ByteBuffer.allocate(512);
            int bytes = socketChannel.read(byteBuffer);
            while (bytes != -1) {
                if (bytes > 0) {
                    byteBuffer.flip();
                    String data = new String(byteBuffer.array(), "UTF-8");
                    syso(data);
                    byteBuffer.clear();
                }
                bytes = socketChannel.read(byteBuffer);
            }
            byteBuffer.clear();
            byteBuffer.put("response...".getBytes("UTF-8"));
            byteBuffer.flip();
            socketChannel.write(byteBuffer);
            socketChannel.shutdownOutput();
            socketChannel.close();
        }
    }
}
